<template>
  <div class="app-container">
    <div class="sidebar">
      <div class="account-div">
        <div class="account" style="padding-top: 20px;">Account:</div>
        <div class="account"
             style="white-space:normal;
             word-break:break-all;
             overflow:hidden;font-weight: bold;">
          {{name}}
        </div>
        <div class="account">Balance:</div>
        <div class="account" style="font-weight: bold;color: red;">${{balance}}</div>
      </div>
      <el-menu
        @select="handleSelect"
        default-active="1"
        class="el-menu-vertical-demo">
        <el-menu-item index="0">
          <i class="el-icon-s-home"></i>
          <span slot="title">Home</span>
        </el-menu-item>
        <el-menu-item index="1">
          <i class="el-icon-document-add"></i>
          <span slot="title">Ad Listing</span>
        </el-menu-item>
        <el-menu-item index="2">
          <i class="el-icon-plus"></i>
          <span slot="title">Recharge Records</span>
        </el-menu-item>
        <el-menu-item index="3">
          <i class="el-icon-refresh"></i>
          <span slot="title">Consume Records</span>
        </el-menu-item>
        <el-menu-item index="4">
          <i class="el-icon-menu"></i>
          <span slot="title">Buy credits</span>
        </el-menu-item>
        <el-menu-item index="5">
          <i class="el-icon-s-custom"></i>
          <span slot="title">Change Password</span>
        </el-menu-item>
        <el-menu-item index="6">
          <i class="el-icon-user"></i>
          <span slot="title">LogOut</span>
        </el-menu-item>
      </el-menu>
    </div>
    <div class="main-content">
      <div v-if="current == 1">
        Ad List

        <!-- 查询条件 -->
        <el-form :model="queryParamsAd" ref="queryForm" :inline="true" label-width="68px">
          <el-form-item label="title" prop="title">
            <el-input v-model="queryParamsAd.title" placeholder="Please input title" clearable size="small"
                      @keyup.enter.native="getListAd" />
          </el-form-item>
          <el-form-item label="phone" prop="phone">
            <el-input v-model="queryParamsAd.phone" placeholder="Please input phone" clearable size="small"
                      @keyup.enter.native="getListAd" />
          </el-form-item>
          <el-select v-model="queryParamsAd.category" placeholder="Please Select category">
            <el-option v-for="category in categorys" :label="category.name" :value="category.id" :key="category.id"/>
          </el-select>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="getListAd">Search</el-button>
          </el-form-item>
        </el-form>

        <el-table v-loading="loading" :data="advertisedList">
<!--          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="id" align="center" prop="id" />-->
          <el-table-column label="title" header-align="center" align="left" prop="title" min-width="100%">
            <template slot-scope="scope">
              <router-link target="_blank" :to="'/cmsDetail?id=' + scope.row.id" class="link-type">
                <span>{{ scope.row.title }}</span>
              </router-link>
            </template>
          </el-table-column>
          <el-table-column label="category" align="center" prop="category" width="100">
            <template slot-scope="scope">
              <span v-if="scope.row.category == 2">Bodyrubs</span>
              <span v-if="scope.row.category == 3">Escorts</span>
            </template>
          </el-table-column>
          <el-table-column label="location" align="center" prop="location" width="100"/>
          <el-table-column label="city" align="center" prop="city" width="100"/>
<!--          <el-table-column label="age" align="center" prop="age" />
          <el-table-column label="phone" align="center" prop="phone" />-->
          <el-table-column label="options" align="center" class-name="small-padding fixed-width" width="230">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
              >update</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-refresh"
                @click="handleRefresh(scope.row)"
              >refresh</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
              >delete</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="totalAd>0"
          :total="totalAd"
          :page.sync="queryParamsAd.pageNum"
          :limit.sync="queryParamsAd.pageSize"
          @pagination="getListAd"
        />
      </div>

      <div v-if="current == 2">
        Recharge Record
        <el-table v-loading="creditsLoading" :data="creditsList">
<!--          <el-table-column type="selection" width="55" align="center" />-->
          <el-table-column label="id" align="center" prop="id" />
          <el-table-column label="bitcoin" align="center" prop="bitcoin" />
          <el-table-column label="usd" align="center" prop="usd" />
          <el-table-column label="status" align="center" prop="status">
            <template slot-scope="scope">
              <span v-if="scope.row.status == 0">unaudited</span>
              <span v-if="scope.row.status == 1">audited</span>
            </template>
          </el-table-column>
          <el-table-column label="transferTime" align="center" prop="transferTime" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.transferTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="totalCredits>0"
          :total="totalCredits"
          :page.sync="queryParamsCredits.pageNum"
          :limit.sync="queryParamsCredits.pageSize"
          @pagination="getCreditsList"
        />
      </div>

      <div v-if="current == 3">
        Consume Record
        <el-table v-loading="loadingLogList" :data="logList">
          <el-table-column label="id" align="center" prop="id" />
          <el-table-column label="type" align="center" prop="type" />
          <el-table-column label="consumeAmount" align="center" prop="consumeAmount" />
          <el-table-column label="actionTime" align="center" prop="actionTime" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.actionTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>

      <div v-if="current == 4">
        <div class="margin-container">
          <img src="./assets/img/bit.jpg" alt="Sample Image" class="center-image">
        </div>

        <el-form ref="bitForm" :model="bitForm" :rules="bitRules" class="login-form">
          <div class="loginTitle1">Amount(USD)</div>
          <el-form-item prop="usd">
            <el-input
              class="input"
              v-model="bitForm.usd"
              type="text"
              auto-complete="off"
              @blur="blurUsd()"
              placeholder="Please enter amount"
            >
            </el-input>
          </el-form-item>
          <div class="loginTitle1">Bitcoin</div>
          <el-form-item prop="bitcoin">
            <el-input
              class="input"
              v-model="bitForm.bitcoin"
              type="text"
              auto-complete="off"
              placeholder="Please enter amount"
              readonly
            >
            </el-input>
          </el-form-item>
          <div class="loginTitle1">Transfer Time</div>
          <el-form-item prop="transferTime">
            <el-date-picker
              v-model="bitForm.transferTime"
              type="datetime"
              placeholder="Select datetime">
            </el-date-picker>
          </el-form-item>
          <div class="loginTitle1">Recharge Voucher</div>
          <el-form-item prop="rechargeFile">
            <el-upload
              :action="imgUpload.url"
              :headers="imgUpload.headers"
              :on-success="handlePictureSuccess"
              :before-upload="beforePictureUpload"
              :limit="1"
              list-type="picture-card"
              :file-list="fileListShow"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-exceed="handleExceed">
              <i class="el-icon-plus"></i>
            </el-upload>
            <!--图片预览的dialog-->
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl">
            </el-dialog>
          </el-form-item>
          <el-form-item style="width:200px;">
            <el-button
              :loading="loading"
              size="medium"
              type="primary"
              style="width:100%; background: linear-gradient(#FF3A90 0%, #C6044B 100%); border-radius: 4px;"
              @click.native.prevent="handleCharge"
            >
              <span v-if="!loading">Charge</span>
              <span v-else>Logging...</span>
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <div v-if="current == 5">
        Change Password
        <resetPwd :user="user" />
      </div>

    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { credits, getBtb, listAdvertised, updateTime, deleteAd } from "@/api/cms/ad"
import { getToken } from "@/utils/auth";
import { listLog } from "@/api/system/log";
import { listCredits } from "@/api/system/credits";
import { register } from "@/api/login";
import resetPwd from "@/views/system/user/profile/resetPwd.vue";
import { getUserProfile } from "@/api/system/user";
import { getIntegral } from '@/api/login'

export default {
  components: {resetPwd},
  data() {
    const equalToPassword = (rule, value, callback) => {
      if (this.registerForm.password !== value) {
        callback(new Error("The two entered passwords do not match"));
      } else {
        callback();
      }
    };
    return {
      user: {},
      creditsLoading: false,
      loadingLogList: false,
      loading: false,
      bitForm: {
        usd: 0,
        bitcoin: 0
      },
      bitRules: {
        usd: [
          { required: true, trigger: "blur", message: "Please enter amount(USD)" },
        ],
      },
      imgUpload: {
        // 设置上传的请求头部
        headers: {
          Authorization: "Bearer " + getToken()
        },
        // 图片上传的方法地址:
        url: process.env.VUE_APP_BASE_API + "/common/upload1",
        url2: process.env.VUE_APP_BASE_API,
      },
      fileListPut: [],
      dialogImageUrl: '',
      dialogVisible: false,
      //修改时此属性用于接收数据库中图片存储list，图片才能正常显示
      fileListShow: [],
      fileList: [],
      // 当前菜单选中
      current: 1,
      // 当前账户余额
      balance: 0.00,
      // 总条数
      total: 0,
      totalCredits: 0,
      // 用户消费记录表格数据
      logList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        adId: null,
        rechargeAmount: null,
        rechargeTime: null,
        consumeAmount: null,
        actionTime: null,
        type: null,
      },
      creditsList: [],
      // 查询参数
      queryParamsCredits: {
        pageNum: 1,
        pageSize: 10,
        account: null,
        bitcoin: null,
        usd: null,
        status: null,
        rechargeFile: null,
        transferTime: null,
      },
      registerForm:{
        password: "",
        confirmPassword: "",
      },
      registerRules: {
        password: [
          { required: true, trigger: "blur", message: "Please enter your password" },
          { min: 5, max: 20, message: 'Passwords must be between 5 and 20 in length', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, trigger: "blur", message: "Please enter your confirmPassword" },
          { required: true, validator: equalToPassword, trigger: "blur" }
        ]
      },
      // 总条数
      totalAd: 0,
      // 广告表格数据
      advertisedList: [],
      // 查询参数
      queryParamsAd: {
        pageNum: 1,
        pageSize: 10,
        category: 4
      },
      categorys: [{
        id: 2,
        name: 'Bodyrubs'
      }, {
        id: 3,
        name: 'Escorts'
      }, {
        id: 4,
        name: 'All'
      }],
    }
  },
  computed: {
    ...mapGetters([
      'name'
    ]),
  },
  created() {
    this.getUser();
  },
  methods: {
    /** 打开编辑页面 */
    handleUpdate(row) {
      this.$router.push({
        path: "/cmsPublishUpdate?id=" + row.id
      });
    },
    handleRefresh(row) {
      updateTime(row.id).then(res => {
        this.getListAd()
        this.$message.success('Refresh publish time success!')
      })
    },
    handleDelete(row) {
      this.$modal.confirm('Whether to confirm the AD?').then(function() {
        return deleteAd(row.id);
      }).then(() => {
        this.getListAd();
        this.$modal.msgSuccess("Delete Success");
      }).catch(() => {});
    },
    /** 查询广告列表 */
    getListAd() {
      this.loading = true;
      listAdvertised(this.queryParamsAd).then(response => {
        this.advertisedList = response.rows;
        this.totalAd = response.total;
        this.loading = false;
      });
    },
    getUser() {
      getUserProfile().then(response => {
        this.user = response.data;
      });
    },
    handleRegister() {
      this.$refs.registerForm.validate(valid => {
        if (valid) {
          this.loading = true;
          register(this.registerForm).then(res => {
            const username = this.registerForm.username;
            this.$alert("<font color='red'>Congratulations, your account " + username + " Registration is successful！</font>", 'System prompts', {
              dangerouslyUseHTMLString: true,
              type: 'success'
            }).then(() => {
              this.$router.push("/cmsLogin");
            }).catch(() => {});
          }).catch(() => {
            this.loading = false;
            if (this.captchaOnOff) {
              this.getCode();
            }
          })
        }
      });
    },
    /** 查询比特币充值凭证列表 */
    getCreditsList() {
      this.creditsLoading = true;
      listCredits(this.queryParamsCredits).then(response => {
        this.creditsList = response.rows;
        this.totalCredits = response.total;
        this.creditsLoading = false;
      });
    },
    /** 查询用户消费记录列表 */
    getList() {
      this.loadingLogList = true;
      listLog(this.queryParams).then(response => {
        this.logList = response.rows;
        this.total = response.total;
        this.loadingLogList = false;
      });
    },
    // 返回前台首页
    toIndex() {
      this.$router.push({
        path: "/cms/main/cmsIndex"
      });
    },
    handleSelect(index) {
      // 处理菜单点击
      this.current = index
      if (index == 0) {
        this.toIndex()
      } else if (index == 1) {
        // 广告列表
        this.getListAd()
      } else if (index == 2) {
        // 充值记录
        this.getCreditsList()
      } else if (index == 3) {
        // 查询消费列表
        this.getList()
      } else if (index == 4) {
        // 账户充值
      } else if (index == 5) {
        // 修改密码
      } else if (index == 6) {
        this.logout()
      }
    },
    logout() {
      this.$confirm('Are you sure to log out and exit the system？', 'tip', {
        confirmButtonText: 'Ok',
        cancelButtonText: 'Cancle',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('LogOut').then(() => {
          location.href = '/index';
        })
      }).catch(() => {});
    },
    //图片上传前的相关判断
    beforePictureUpload(file) {
      //每次进来初始化 isCommonName 为true
      this.isCommonName = true;
      const isJPG = file.type === 'image/jpeg';
      const isLt1M = file.size / 1024 / 1024 < 1;
      const countImg = this.fileListPut.length <= 1;
      //判断是否有相同的图片，如何有即提示并添加失败
      if(this.fileListPut.length > 0){
        this.fileListPut.forEach((item,index)=>{
          if(item.name == file.name){
            this.$message.error('The same image already exists！');
            this.isCommonName = false;
          }
        })
      }
      if (!countImg) {
        this.$message.error('You can upload up to 1 image！');
      }
      if (!isJPG) {
        this.$message.error('Please upload a file in image format！');
      }
      if (!isLt1M) {
        this.$message.error('Uploaded images cannot exceed 1MB!');
      }
      return countImg && isJPG && isLt1M && this.isCommonName;
    },
    //图片上传删除
    handleRemove(file, fileList) {
      // 删除图片数组
      this.fileList = this.fileList.filter(function(item) {
        return item !== file.response.fileId
      });
      //根据传进来删除的file里图片，同时删除保存在fileListPut的相同图片
      if(this.fileListPut.length > 0){
        this.fileListPut = this.fileListPut.filter((item, index)=>{
          return item.name != file.name;
        })
      }
    },
    // 图片数量超过限制
    handleExceed() {
      this.$message.warning('You can upload up to 30 images！');
    },
    //图片预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //图片上传成功后的回调
    handlePictureSuccess(res, file) {
      this.fileList.push(res.fileId)
      //this.fileList.push(file)
      //设置图片访问路径
      const imgObjectUrl = this.imgUpload.url2 + file.response.fileName;
      //这是每个成功上传图片，以对象的形式保存在一个数组中，进而以JSON格式保存在数据库中某个字段里
      let currentFile = {name: '',url: ''};
      currentFile.name = file.name;
      currentFile.url = imgObjectUrl;
      // 往此数组中保存当前图片对象
      this.fileListPut.push(currentFile);
    },
    // 通过汇率计算充值金额
    blurUsd() {
      getBtb({usd: this.bitForm.usd}).then(res => {
        console.log(res)
        this.bitForm.bitcoin = res.data
      })
    },
    // 充值
    handleCharge() {
      var that = this
      this.$refs.bitForm.validate(valid => {
        if (valid) {
          if (that.fileList.length < 1) {
            that.$modal.msgError("charge failure")
            return
          }
          that.bitForm.rechargeFile = that.fileList[0]
          credits(this.bitForm).then(res => {
            if(res.code == 200) {
              that.$modal.msgSuccess("charge success")
            } else {
              that.$modal.msgError("charge failure")
            }
          }).catch(error => {
            reject(error)
          })
        }
      })
    }
  },
  mounted() {
    // 获取账户余额
    getIntegral().then(res => {
      this.balance = res.data
    }).catch(error => {
      reject(error)
    })
    this.getListAd()
  }
}
</script>

<style>
.center-image {
  display: block;
  margin: auto;
  width: 400px;
  height: 640px;
}

.margin-container {
  text-align: center;
}

.sidebar {
  width: 200px;
  background-color: #FF3A90;
  height: 100vh;
  position: fixed;
  left: 0;
  top: 0;
}

.menu-item {
  padding: 10px;
  border-bottom: 1px solid #ddd;
}

.menu-item a {
  text-decoration: none;
  color: #333;
  display: block;
}

.menu-item a.router-link-exact-active {
  color: #42b983;
  font-weight: bold;
}

.app-container {
  display: flex;
}

.main-content {
  flex: 1;
  margin-left: 200px;
  padding: 20px;
}

.account {
  margin: 8px 10px;
}

.account-div {
  font-size: 22px;
  width: 100%;
  height: 180px;
  background-color: white;
  margin: 0px 0px 10px 0px;
  padding: 0px 5px 0px 5px;
}
</style>
